package com.sc.nft.controller;


import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sc.nft.annotation.UserLogin;
import com.sc.nft.controller.request.IdPageRequest;
import com.sc.nft.controller.request.IdRequest;
import com.sc.nft.controller.request.MyAuctionRequest;
import com.sc.nft.controller.request.SupplementarySignatureRequest;
import com.sc.nft.dao.ActivityTaskUserPriceDao;
import com.sc.nft.dto.UserAuctionBiddingDTO;
import com.sc.nft.entity.ActivityBasics;
import com.sc.nft.entity.ActivityTaskPlan;
import com.sc.nft.entity.ActivityTaskUserPrize;
import com.sc.nft.entity.UserInfo;
import com.sc.nft.entity.vo.*;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.pool.UserPool;
import com.sc.nft.service.ActivityBasicsService;
import com.sc.nft.service.ActivityTaskPlanService;
import com.sc.nft.service.DigitalCollectionProductInfoAuctionService;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.sup.PageRequest;
import com.sc.nft.sup.PageResult;
import com.sc.nft.sup.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/home/auction")
@Api(tags = "拍卖接口")
public class AuctionController {
    /**
     * 服务对象
     */
    private final DigitalCollectionProductInfoAuctionService digitalCollectionProductInfoAuctionService;
    private final Redisson redisson;

    @ApiOperation(value = "用户拍卖记录", notes = "用户拍卖记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/records", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public PageResult<UserAuctionRecordPageVO> auctionRecords(@RequestBody PageRequest pageRequest) {
        return PageResult.success(digitalCollectionProductInfoAuctionService.auctionRecords(UserPool.getUser().getId(),pageRequest.toMp()));
    }

    @ApiOperation(value = "单个拍卖记录详情", notes = "单个拍卖详情", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/details", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result<UserAuctionRecordDetailsVO> auctionDetails(@Valid @RequestBody IdRequest idRequest) {
        return Result.success(digitalCollectionProductInfoAuctionService.auctionDetails(UserPool.getUser().getId(),idRequest.getId()));
    }

    @ApiOperation(value = "我的质押物", notes = "我的质押物", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/pledgeItems", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result<UserAuctionPledgeVO> auctionPledgeItems(@Valid @RequestBody IdRequest idRequest) {
        return Result.success(digitalCollectionProductInfoAuctionService.auctionPledgeItems(UserPool.getUser().getId(),idRequest.getId()));
    }


    @ApiOperation(value = "中标名单", notes = "中标名单", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/winList", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public PageResult<UserAuctionWinVO> auctionWinList(@Valid @RequestBody MyAuctionRequest request) {
        return PageResult.success(digitalCollectionProductInfoAuctionService.auctionWinList(request.getProductId(),request.toMp()));
    }



    @ApiOperation(value = "去参加拍卖活动页面", notes = "去参加拍卖活动页面", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/participation", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result<UserAuctionParticipationVO> auctionParticipation(@Valid @RequestBody IdRequest idRequest) {
        return Result.success(digitalCollectionProductInfoAuctionService.auctionParticipation(idRequest.getId(),UserPool.getUser().getId()));
    }

    @ApiOperation(value = "用户投标", notes = "去参加拍卖活动页面", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/bidding", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result auctionBidding(@Valid @RequestBody UserAuctionBiddingDTO userAuctionBiddingDTO) {
        UserInfo user = UserPool.getUser();
        if (!userAuctionBiddingDTO.getPaymentPassword().equals(UserPool.getUser().getTransactionPassword())) {
            throw new GlobalRunTimeException("支付密码错误");
        }
        RLock lock = redisson.getLock(RedisKeyEnum.BID_PRODUCTS_LOCK.getKey() + userAuctionBiddingDTO.getProductId());
        RLock userLock = redisson.getLock(RedisKeyEnum.USER_MERCHANT_PLEDGE_COLLECTION_SECRET_AREA_LOCK.getKey() + user.getId());
        try {
            boolean res = lock.tryLock(10, TimeUnit.SECONDS);
            if (res) {
                boolean userLockRes = userLock.tryLock(10, TimeUnit.SECONDS);
                if(!userLockRes){
                    return Result.fail("请稍后重试!");
                }
                digitalCollectionProductInfoAuctionService.auctionBidding(userAuctionBiddingDTO,user);
            }else{
                return Result.fail("请稍后重试!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new GlobalRunTimeException("系统超时");
        } finally {
            lock.unlock();
            userLock.unlock();
        }
        return Result.success();
    }



    @ApiOperation(value = "获取用户协议", notes = "获取用户协议", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/getRule", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result<String> auctionGetRule() {
        return Result.success(digitalCollectionProductInfoAuctionService.auctionGetRule());
    }


    @ApiOperation(value = "同意用户协议", notes = "获取用户协议", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/user/agreement", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result auctionUserAgreement(@Valid @RequestBody IdRequest idRequest) {
        digitalCollectionProductInfoAuctionService.auctionUserAgreement(idRequest.getId(),UserPool.getUser().getId());
        return Result.success();
    }

}
